package com.cmwa.solution.base.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.cmwa.ec.base.util.SpringUtil;
import com.cmwa.solution.base.entity.OAuthEntity;
import com.cmwa.solution.utils.HttpClientUtil;
import com.cmwa.solution.utils.JsonUtil;
import com.cmwa.solution.utils.RSASignature;
import com.cmwa.solution.utils.SessionUtils;

@Controller
@RequestMapping("/oauth2")
public class OAuth2Controller extends BaseController {
	
	private static final Log logger = LogFactory.getLog(OAuth2Controller.class);
	
	private static final String PRIVATE_KEY_PATH = "/privateKeyFile";
	
	@RequestMapping("/leadToAuthorize")
    public void leadToAuthorize(@RequestParam("redirectUrl") String redirectUrl, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String empId = SessionUtils.getEmployee().getID();
		String msg = "appId=S101002&userId=" + empId + "&ip=" + getIpAddr(request) + "&timestamp=" + System.currentTimeMillis();
		String sign = RSASignature.sign(msg, RSASignature.loadKeyFromFile(System.getProperty("appHome") + PRIVATE_KEY_PATH));
		msg = msg + "&sign=" + sign;
		
		String rsTokenUrl = SpringUtil.getProperty("sys.rsTokenUrl");
		logger.info("rsTokenUrl:" + rsTokenUrl);
		logger.info("msg:" + msg);
		
		String result = HttpClientUtil.postMsg(rsTokenUrl, msg);
		
		logger.info("result:" + result);
		if(StringUtils.isNotBlank(result)) {
			OAuthEntity auth = JsonUtil.parseJson(result, OAuthEntity.class);
	        if(auth != null) {
	        	if(auth.isSuccess()) {
	        		response.sendRedirect(redirectUrl + "?token=" + auth.getMsg());
	        	} else {  //  请求失败
	        		
	        	}
	        } else {  // json转换失败
	        	
	        }
		} else {  // 请求失败
			
		}
	}
}
